<?php
/**
*2018-05-05	14:40	wdj	登录控制器
*/
namespace app\index\controller;

use think\Controller;
use \think\Db;
use \think\Cache;
use \think\Session;

class Login extends Controller
{

	public $appid		=	"wxfff70773494b17e4";
    public $secret		=	"3b3033d855cd2946290ec4e8e104dd67";
	/**
	*代理商统一登录地址
	*微信后台，网页版	
	*登录之后绑定openID
	*/
	public function login()
	{
		if($this->request->isPost()){
			//是登录操作
            $post = $this->request->post();
            //验证  唯一规则： 表名，字段名，排除主键值，主键名
            $validate = new \think\Validate([
                ['name', 'require|alphaDash', '用户名不能为空|用户名格式只能是字母、数字、——或_'],
                ['password', 'require', '密码不能为空'],
                 ['captcha','require|captcha','验证码不能为空|验证码不正确'],
            ]);
            //验证部分数据合法性
            if (!$result = $validate->check($post)) {
                return $this->error($validate->getError());
            }

            $agent 	=	Db::name('agent')->where(['phone' => $post['name']])->field('id , name , phone ,password, openid')->find();
           
            if(empty($agent)) {
                return $this->error('用户不存在');
            }
            if($agent['password'] != password($post['password'])) {
                return $this->error('密码错误');
            }

          
            $pid = Db::name('ratio')->where('agent_id',$agent['id'])->value('grade');
            //设置session
            Session::set('pid' , $pid);
            Session::set('agentInfo.id' , $agent['id']);
            Session::set('agentInfo.name' , $agent['name']);
            Session::set('agentInfo.phone' , $agent['phone']);
            Session::set('agentInfo.openid' , $agent['openid']);
            // Session::get();exit;
            return $this->success('登录成功，正在跳转.....' , 'index/Agent/index');
		}else{	
			//判断是否微信浏览器登录,如果有关注公众号的话直接进入，如果没有还是走登录
			if(strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger')){
				$this->silentLogin();
			}else{
				return $this->fetch();
			}					
		}
	}
		public function index()
	{
		if($this->request->isPost()){
			//是登录操作
            $post = $this->request->post();
            //验证  唯一规则： 表名，字段名，排除主键值，主键名
            $validate = new \think\Validate([
                ['name', 'require|alphaDash', '用户名不能为空|用户名格式只能是字母、数字、——或_'],
                ['password', 'require', '密码不能为空'],
                 ['captcha','require|captcha','验证码不能为空|验证码不正确'],
            ]);
            //验证部分数据合法性
            if (!$result = $validate->check($post)) {
                return $this->error($validate->getError());
            }

             $agent 	=	Db::name('agent')->where(['phone' => $post['name']])->field('id , name , password,phone , openid')->find();
           
            if(empty($agent)) {
                return $this->error('用户不存在');
            }
            if($agent['password'] != password($post['password'])) {
                return $this->error('密码错误');
            }

            $pid = Db::name('ratio')->where('agent_id',$agent['id'])->value('grade');
            //设置session
            Session::set('pid' , $pid);
            Session::set('agentInfo.id' , $agent['id']);
            Session::set('agentInfo.name' , $agent['name']);
            Session::set('agentInfo.phone' , $agent['phone']);
            Session::set('agentInfo.openid' , $agent['openid']);
            // Session::get();exit;
            return $this->success('登录成功，正在跳转.....' , 'index/agent/index');
		}else{	
			//判断是否微信浏览器登录,如果有关注公众号的话直接进入，如果没有还是走登录
			if(strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger')){
				$this->silentLogin();
			}else{
				return $this->fetch();
			}					
		}
	}

	/**
	*	通过静默授权方式得到该用户的关注信息
	*	
	*/
	protected function silentLogin()
	{
		$callbackUrl	=	urlencode('http://csmj.qiligame.com/index/Login/silentCallback');
        
        $url 			= 	'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $this->appid . '&redirect_uri=' . $callbackUrl . '&response_type=code&scope=snsapi_base&state=wx#wechat_redirect';


        header("Location:".$url);
        exit();
	}

	/**
	*	静默授权回调地址
	*	o8Idl1JEHSRAoGWIHtuPDDOEoswk
	*/
	public function silentCallback()
	{

		//通过获取到的code之后然后根据code获取access_token
		if(input('get.code')){
			$code 		=	input('get.code');
			$accessUrl	=	'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $this->appid . '&secret=' . $this->secret . '&code=' .$code. '&grant_type=authorization_code';

			$accessInfo	=	json_decode(request_get($accessUrl) , true);
		
			
			
			$openid 	=	$accessInfo['openid'] ;
			$access_token =	Cache::get('access_token') ? Cache::get('access_token') : $this->getAccess();

			$ifBond	=	Db::name('agent')->where(['openid' => $openid])->find();
			if($ifBond){
				$adminInfo	=	Db::name('admin')->where(['name' => $ifBond['phone']])->field('id , admin_cate_id')->find();
				$agent 		=	Db::name('agent')->where(['phone' => $ifBond['phone']])->field('id , name , phone , openid')->find();
			  $pid = Db::name('ratio')->where('agent_id',$agent['id'])->value('pid');
            //设置session
                  Session::set('pid' , $pid);
	          
	            Session::set('agentInfo.id' , $agent['id']);
	            Session::set('agentInfo.name' , $agent['name']);
	            Session::set('agentInfo.phone' , $agent['phone']);
	            Session::set('agentInfo.openid' , $agent['openid']);
				$this->redirect('index/Agent/index');
			}else{
				return $this->fetch('login');
			}
			/*//根据openid判断是否已经关注
			$infoUrl	=	"https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $access_token . "&openid=" . $openid . "&lang=zh_CN";	
			$openInfo	=	json_decode(request_get($infoUrl) , true);
			
			//如果subscribe等于1，说明已经订阅了
			if($openInfo['subscribe'] == 1){
				$ifBond	=	Db::name('agent')->where(['openid' => $openInfo['openid']])->find();
				if($ifBond){
					$adminInfo	=	Db::name('admin')->where(['name' => $ifBond['phone']])->field('id , admin_cate_id')->find();
					$agent 		=	Dn::name('agent')->where(['phone' => $ifBond['name']])->field('id , name , phone , openid')->find();
					//设置session
		            session::set('admin' , $adminInfo['id']);
		            session::set('admin_cate_id' , $adminInfo['admin_cate_id']);
		            Session::set('agentInfo.id' , $agent['id']);
		            Session::set('agentInfo.name' , $agent['name']);
		            Session::set('agentInfo.phone' , $agent['phone']);
		            Session::set('agentInfo.openid' , $agent['openid']);
					$this->success('登录成功，正在跳转.....' , 'index/Agent/index');
				}else{
					return $this->fetch('login');
				}
			}else{
				return $this->fetch('login');
			}*/
		}
	}

	

	/**
    *   代理商绑定二维码
    */
    public function bondPublic()
    {
        // $openid     =   Session::get('agentInfo')['openid'];
        $openid 	   =	Db::name('agent')->where(['id' => Session::get('agentInfo')['id']])->value('openid');			
        if($openid){
            return $this->success('已经成功绑定过公众号！！！');
        }
        //代理商的ID
        $agent_id   =   Session::get('agentInfo')['id'];
        $callbackUrl    =   urlencode('http://csmj.qiligame.com/index/Login/bondCallback?agent_id='.$agent_id);
        
        $url            =   'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $this->appid . '&redirect_uri=' . $callbackUrl . '&response_type=code&scope=snsapi_base&state=State#wechat_redirect';
        header("Location:".$url);
        exit();
    }

	/**
	*	绑定公众号回调地址
	*/
	public function bondCallback()
	{
		//同时获取到code和adminId
		if(input('get.code') && input('get.agent_id')){
			$code 		=	input('get.code');
			$agent_id 	=	input('get.agent_id');
			$accessUrl	=	'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $this->appid . '&secret=' . $this->secret . '&code=' .$code. '&grant_type=authorization_code';
			$accessInfo	=	json_decode(request_get($accessUrl) , true);

			if($accessInfo['openid']){
				$result	=	Db::name('agent')->where(['id' => intval($agent_id)])->update(['openid' => $accessInfo['openid']]);
				// echo Db::name('agent')->getLastSql();exit;
				if($result !== false){
					 Session::set('agentInfo.openid' , $accessInfo['openid']);
					return $this->success('绑定成功' , 'index/Agent/index');
				}else{
					return $this->error('绑定失败' , 'index/Agent/index');
				}
			}else{
				return $this->error('请先关注公众号' , 'index/Agent/index');
			}

			/*$access_token =	Cache::get('access_token') ? Cache::get('access_token') : $this->getAccess();
			//根据openid判断是否已经关注
			$infoUrl	=	"https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $access_token . "&openid=" . $accessInfo['openid'] . "&lang=zh_CN";	
			$openInfo	=	json_decode(request_get($infoUrl) , true);
			// dump($openInfo);exit;
			if($openInfo['subscribe'] == 1){
				//代理商绑定公众号的openid 
				$result	=	Db::name('agent')->where(['id' => intval($agent_id)])->update(['openid' => $openInfo['openid']]);
				if($result == false){
					return $this->success('绑定成功' , 'index/Agent/index');
				}else{
					return $this->error('绑定失败' , 'index/Agent/index');
				}
			}else{
				return $this->error('请先关注公众号' , 'index/Agent/index');
			}*/
		}
	}

	/**
	*获取access_token，全局通用，与授权登录的access_token不同
	*/
	private function getAccess()
	{
		$accessUrl	=	"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" .$this->appid. "&secret=".$this->secret;
		$accessInfo =	json_decode(request_get($accessUrl) , true);
		Cache::set('access_token' , $accessInfo['access_token'] , $accessInfo['expires_in']);
		return $accessInfo['access_token'];
	}
}
